<template>
  <div class="app-container bg">
    <div class="box-container">
      <el-radio-group v-model="showType" @change="showTypeChange">
        <el-radio-button label="1">科室</el-radio-button>
        <el-radio-button label="2">学员</el-radio-button>
      </el-radio-group>
      <el-row
        :gutter="10"
        class="mb15 flex-container"
        style="font-size: 14px; line-height: 25px"
      >
        <el-col :span="2.5">
          <div
            @click="clickAll(0, null)"
            class="nactive"
            :class="{ active: tagIndex == 0 }"
          >
            全部：{{ orderStats.allState || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(1, { noPayStat: 1 })"
            class="nactive"
            :class="{ active: tagIndex == 1 }"
          >
            待支付：{{ orderStats.noPayStat || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(2, { paidStat: 1 })"
            class="nactive"
            :class="{ active: tagIndex == 2 }"
          >
            已支付：{{ orderStats.paidStat || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(3, { refundInApprovalStat: 1 })"
            class="nactive"
            :class="{ active: tagIndex == 3 }"
          >
            退款待审核：{{ orderStats.refundInApprovalStat || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(4, { refundCompletedStat: 1 })"
            class="nactive"
            :class="{ active: tagIndex == 4 }"
          >
            已退款：{{ orderStats.refundCompletedStat || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(5, { onlinePayStat: 1 })"
            class="nactive"
            :class="{ active: tagIndex == 5 }"
          >
            线上缴费：{{ orderStats.onlinePayStat || 0 }}
          </div>
        </el-col>
        <el-col :span="2.5">
          <div
            @click="clickAll(6, { offlinePayStat: 1 })"
            class="nactive"
            :class="{ active: tagIndex == 6 }"
          >
            线下缴费：{{ orderStats.offlinePayStat || 0 }}
          </div>
        </el-col>
      </el-row>
    </div>
    <el-form
      class="box-container"
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="" style="width: 160px" prop="registerDeptId">
        <el-select
          v-model="queryParams.registerDeptId"
          placeholder="请选择进修科目"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerDeptList"
            :key="index"
            :label="item.registerDeptName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="batchName">
        <el-select
          v-model="queryParams.batchName"
          placeholder="请选择招生批次"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerBatchList"
            :key="index"
            :label="item.name"
            :value="item.name"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="registerYear">
        <el-date-picker
          v-model="queryParams.registerYear"
          type="year"
          placeholder="请选择招生年份"
          format="yyyy"
          style="width: 160px"
          value-format="yyyy"
          @change="handleQuery"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label=""
        style="width: 160px"
        prop="userName"
        v-if="showType == 2"
      >
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入姓名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="sourceUnitType">
        <el-select
          v-model="queryParams.sourceUnitType"
          placeholder="选择生源单位类型"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in sourceUnitTypeList"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="" style="width: 160px" prop="durationName">
        <el-select
          v-model="queryParams.durationName"
          placeholder="请选择进修时长"
          filterable
          clearable
          @change="handleQuery"
        >
          <el-option
            v-for="(item, index) in registerPeriodList"
            :key="index"
            :label="item.name"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
      <el-form-item v-if="showType == 2">
        <el-button type="primary" size="mini" @click="exportData"
          >导出</el-button
        >
        <el-button type="primary" size="mini" @click="refundReview"
          >退款审核</el-button
        >
      </el-form-item>
    </el-form>
    <div class="box-container">
      <div v-if="showType == 1" class="custom-table">
        <div class="custom-dept" v-for="(row, index) in dataList" :key="index">
          <div class="colw title">{{ row.registerDeptName }}</div>
          <div class="colw flex">
            <div class="col">
              {{ row.allState }}
              <div class="desc">报名总数</div>
            </div>
            <div class="col">
              {{ row.noPayStat }}
              <div class="desc">待支付</div>
            </div>
            <div class="col">
              {{ row.paidStat }}
              <div class="desc">已支付</div>
            </div>
            <div class="col">
              {{ row.refundCompletedStat }}
              <div class="desc">已退款</div>
            </div>
          </div>
          <div class="colw func" @click="viewOpen(row)">
            <el-button size="small" type="primary">查看名单</el-button>
          </div>
        </div>
      </div>
      <div v-if="showType == 2" class="custom-table">
        <el-checkbox
          v-model="AllCheck"
          @change="handleSelectionChangeAll"
          style="transform: scale(1.2); margin-bottom: 20px; margin-left: 20px"
          >全选</el-checkbox
        >
        <div
          class="custom-register"
          v-for="(row, index) in dataList"
          :key="index"
        >
          <div class="col border" style="display: flex">
            <div class="user-name">
              <div style="margin-right: 10px">
                <el-checkbox
                  v-model="row.check"
                  style="transform: scale(1.2)"
                  @change="handleSelectionChange($event, index)"
                />
              </div>
              <span
                style="
                  font-size: 18px;
                  font-weight: bolder;
                  color: #a52529;
                  cursor: pointer;
                "
                @click="detailOpen(row)"
                >{{ row.userName }}</span
              >
              <el-tag
                size="small"
                :color="getStatusTag(row).color"
                style="
                  margin-left: 10px;
                  width: auto;
                  color: #fff;
                  border: none;
                "
              >
                {{ getStatusTag(row).text }}</el-tag
              >
              <div style="margin-left: auto; font-size: 12px; color: #999">
                工号：{{ row.registerNotice && row.registerNotice.jobNumber }}
              </div>
            </div>
            <div class="info" style="flex: 1">
              <div class="flexInfo left">
                <div v-if="row.registerInfo">
                  进修科目：{{ row.registerInfo.registerDeptName }}
                </div>
                <div style="display: flex">
                  进修期限：
                  <div v-if="row.registerInfo">
                    {{ row.registerInfo.durationStartDate }} -
                    {{ row.registerInfo.durationEndDate }}
                    <span v-if="row.registerInfo.durationName"
                      >（{{ row.registerInfo.durationName }}）</span
                    >
                  </div>
                </div>
                <div>
                  最晚缴费时间：{{
                    getLatestPaymentDate(
                      row.registerNotice ? row.registerNotice.startDate : null
                    )
                  }}
                </div>
                <div v-if="row.paymentStatus === 1">
                  缴费时间：{{ row.paymentTime }}
                </div>
                <div v-if="row.paymentStatus !== 0">
                  缴费方式：{{ row.payDataType === 1 ? "线上" : "线下" }}
                </div>
              </div>
              <div class="flexInfo right">
                <div>进修费用：{{ row.engageAmount }}</div>
                <div>实验费用：{{ row.materialAmount }}</div>
                <div v-if="row.joinMicrosutureAmount > 0">
                  显微血管缝合操作培训费用：{{ row.joinMicrosutureAmount }}
                </div>
                <div>
                  合计费用：{{
                    (row.engageAmount || 0) +
                    (row.materialAmount || 0) +
                    (row.joinMicrosutureAmount || 0)
                  }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      title="报名详情"
      :visible.sync="detailShowInfo"
      width="1040px"
      append-to-body
      :close-on-click-modal="false"
    >
      <registerInfoDetailInfo
        v-if="detailShowInfo"
        :register-id="registerInfo.id"
      />
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailShowInfo = false">关 闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { consts } from "@/api/business/consts";
import {
  getCountOrder,
  getDepartmentStatList,
  listAllOrder,
  refundReview,
} from "@/api/business/order";
import { listAllRegisterDept } from "@/api/business/registerDept";
import { listAllRegisterType } from "@/api/business/registerType";
import { setupBatchData } from "@/utils/batchUtils";
import registerInfoDetailInfo from "../audit/components/registerInfoDetailInfo";

/**
 * 订单管理组件
 * 功能：
 * 1. 展示订单状态统计
 * 2. 提供订单查询功能
 * 3. 展示订单列表
 */
export default {
  name: "order",
  components: {
    registerInfoDetailInfo,
  },
  data() {
    return {
      // 根路径
      baseURL: process.env.VUE_APP_BASE_API,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      dataList: [],
      //全选
      AllCheck: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        registerDeptId: null,
        registerTypeId: null,
        batchName: null,
        registerYear: null,
        userName: null,
        sourceUnitType: null,
        durationName: null,
        paymentStatus: null,
        onlinePayStat: null,
        offlinePayStat: null,
      },
      detailShowInfo: false, // 报到详情
      registerInfo: {
        id: null,
      },
      registerDeptList: [],
      registerTypeList: [],
      registerBatchList: [],
      sourceUnitTypeList: consts.sourceUnitTypeList,
      registerPeriodList: [
        { name: "所有进修时长", value: "" },
        { name: "1个月", value: "1个月" },
        { name: "3个月", value: "3个月" },
        { name: "6个月", value: "6个月" },
        { name: "12个月", value: "12个月" },
      ],
      orderStats: {},
      tagIndex: 0,
      statusColors: {
        noPay: "#f1a82b",
        paid: "#8bc323",
        overdue: "#0d0c0c",
        refund: "#ac3f41",
      },
      showType: 1,
    };
  },
  async created() {
    await this.getbatch();
    this.initData();
    this.listAllRegisterDept();
    this.listAllRegisterType();
  },
  methods: {
    async getbatch() {
      await setupBatchData(this);
    },
    /**
     * 初始化数据
     * 1. 获取统计计数
     * 2. 获取列表数据
     */
    initData() {
      this.getCount();
      this.getList();
    },
    clickAll(index, filter) {
      this.tagIndex = index;
      // Reset filters
      this.queryParams.paidStat = null;
      this.queryParams.onlinePayStat = null;
      this.queryParams.offlinePayStat = null;
      this.queryParams.refundCompletedStat = null;
      this.queryParams.refundInApprovalStat = null;
      this.queryParams.noPayStat = null;
      // Apply new filter
      if (filter) {
        if (filter.paidStat !== undefined) {
          this.queryParams.paidStat = filter.paidStat;
        }
        if (filter.noPayStat !== undefined) {
          this.queryParams.noPayStat = filter.noPayStat;
        }
        if (filter.onlinePayStat !== undefined) {
          this.queryParams.onlinePayStat = filter.onlinePayStat;
        }
        if (filter.offlinePayStat !== undefined) {
          this.queryParams.offlinePayStat = filter.offlinePayStat;
        }
        if (filter.refundInApprovalStat !== undefined) {
          this.queryParams.refundInApprovalStat = filter.refundInApprovalStat;
        }
        if (filter.refundCompletedStat !== undefined) {
          this.queryParams.refundCompletedStat = filter.refundCompletedStat;
        }
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    listAllRegisterDept() {
      listAllRegisterDept().then((response) => {
        this.registerDeptList = response.data;
      });
    },
    listAllRegisterType() {
      listAllRegisterType().then((response) => {
        this.registerTypeList = response.data;
      });
    },
    /**
     * 获取各状态统计计数
     * @returns {Promise<void>}
     */
    getCount() {
      getCountOrder(this.queryParams).then((response) => {
        this.orderStats = response.data || {};
      });
    },
    /**
     * 获取列表数据
     * @returns {Promise<void>}
     */
    getList() {
      this.loading = true;
      if (this.showType == 1) {
        getDepartmentStatList(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        listAllOrder(this.queryParams).then((response) => {
          this.dataList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    detailOpen(row) {
      this.registerInfo.id = row.registerInfo.id;
      this.detailShowInfo = true;
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.initData();
    },
    showTypeChange() {
      this.queryParams.registerDeptId = null;
      this.queryParams.userName = null;
      this.handleQuery();
    },
    viewOpen(row) {
      this.showType = "2";
      this.queryParams.registerDeptId = row.registerDeptId;
      this.handleQuery();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // 手动重置批次和年份为空
      this.queryParams.batchName = null;
      this.queryParams.registerYear = null;
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //取消全选
    canselAllcheck() {
      this.AllCheck = false;
      this.ids = [];
      this.single = true;
      this.multiple = true;
    },
    // 全选
    handleSelectionChangeAll(checked) {
      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        // 使用 $set 确保属性被响应式地修改
        this.$set(this.dataList, i, { ...this.dataList[i], check: checked });
        if (checked) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
    // 多选框选中数据
    handleSelectionChange(checked, index) {
      // 使用 $set 确保属性被响应式地修改
      this.$set(this.dataList, index, {
        ...this.dataList[index],
        check: checked,
      });

      let ids = [];
      for (let i = 0; i < this.dataList.length; i++) {
        if (this.dataList[i].check) {
          ids.push(this.dataList[i].id);
        }
      }
      this.ids = ids;
      this.single = ids.length !== 1;
      this.multiple = !ids.length;
    },
    getStatusTag(row) {
      if (row.refundStatus != null) {
        switch (row.refundStatus) {
          case 0:
            if (row.registerApprovalFlow.approverRole === "admin") {
              return {
                text: "退款待管理员审核",
                color: this.statusColors.refund,
              };
            } else if (
              row.registerApprovalFlow.approverRole &&
              ["manage", "secretary"].some((role) =>
                row.registerApprovalFlow.approverRole.split(",").includes(role)
              )
            ) {
              console.log(row.registerApprovalFlow);
              return {
                text: "退款待科室审核",
                color: this.statusColors.refund,
              };
            } else {
              return { text: "退款待审批", color: this.statusColors.refund };
            }
          case 1:
            if (row.registerApprovalFlow.approverRole === "admin") {
              return {
                text: "退款待管理员审核",
                color: this.statusColors.refund,
              };
            } else {
              return {
                text: "退款审批中",
                color: this.statusColors.refund,
              };
            }

          case 2:
            return { text: "退款已审批", color: this.statusColors.refund };
          case 3:
            return { text: "退款已拒绝", color: this.statusColors.refund };
          case 4:
            return { text: "退款执行中", color: this.statusColors.refund };
          case 5:
            return { text: "已退款", color: this.statusColors.refund };
          case 6:
            return { text: "已失败", color: this.statusColors.refund };
          default:
        }
      } else {
        switch (row.paymentStatus) {
          case 0:
            return { text: "待支付", color: this.statusColors.noPay };
          case 1:
            return { text: "已支付", color: this.statusColors.paid };
          case 2:
            return { text: "支付失败", color: this.statusColors.overdue };
          case 3:
            return { text: "已逾期", color: "#909399" };
          case 4:
            return { text: "退款中", color: this.statusColors.refund };
          case 5:
            return { text: "已退款", color: this.statusColors.refund };
        }
      }

      return { text: "未知状态", color: "#909399" };
    },
    getLatestPaymentDate(startDateStr) {
      if (!startDateStr) return "/";
      const [year, month, day] = startDateStr.split("/").map(Number);
      const date = new Date(year, month - 1, day); // 月份转换为0-based
      date.setMonth(date.getMonth() + 1); // 加一个月
      const newYear = date.getFullYear();
      const newMonth = String(date.getMonth() + 1).padStart(2, "0"); // 转换为1-based并补零
      const newDay = String(date.getDate()).padStart(2, "0");
      return `${newYear}/${newMonth}/${newDay}`;
    },
    /** 退款审核 */
    refundReview() {
      if (this.single) {
        this.$message.warning("请每次选择一个订单处理退款");
        return;
      }
      const selectedId = this.ids[0];
      const selectedStudent = this.dataList.find(
        (item) => item.id === selectedId
      );
      if (!selectedStudent) {
        this.$message.error("未找到选中的学员信息");
        return;
      }
      console.log(selectedStudent);
      if (
        selectedStudent.refundStatus !== 0 &&
        selectedStudent.refundStatus !== 1
      ) {
        this.$message.error("请选择处于 “退款待审核” 状态的订单进行审核。");
        return;
      }
      if (
        !selectedStudent.registerApprovalFlow ||
        !selectedStudent.registerApprovalFlow.approvalId
      ) {
        this.$message.error("未找到该学员的退款审批信息");
        return;
      }
      this.$confirm(
        `是否同意 ${selectedStudent.userName} 的退款申请?`,
        "退款审核",
        {
          confirmButtonText: "同意",
          cancelButtonText: "拒绝",
          type: "warning",
          distinguishCancelAndClose: true,
        }
      )
        .then(() => {
          refundReview({
            approvalId: selectedStudent.registerApprovalFlow.approvalId,
            status: 1,
            opinion: "同意",
          }).then(() => {
            this.$message({
              type: "success",
              message: "已同意退款申请!",
            });
            this.getList();
            this.getCount();
          });
        })
        .catch((action) => {
          if (action === "cancel") {
            refundReview({
              approvalId: selectedStudent.registerApprovalFlow.approvalId,
              status: 2,
              opinion: "拒绝",
            }).then(() => {
              this.$message({
                type: "info",
                message: "已拒绝退款申请",
              });
              this.getList();
              this.getCount();
            });
          }
        });
    },
    /** 导出按钮操作 */
    exportData() {
      let queryParams = { ...this.queryParams }; // 创建一个副本，避免修改原始对象
      delete queryParams.pageSize;
      delete queryParams.pageNum;
      this.download(
        "business/registerPaymentOrder/export",
        {
          ...queryParams,
        },
        `导出订单_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
<style lang="scss" scoped>
// 基础变量定义
$border-color: #d8d8d8;
$primary-color: #a52529;
$secondary-color: #606266;
$light-gray: #eeeff4;
$desc-color: #888;

// 通用样式
::v-deep .el-dialog__body {
  padding: 0 20px 20px 20px;
}

// 用户名称样式
.user-name {
  display: flex;
  align-items: center;
  width: 100%;
}

// 容器基础样式
.box-container {
  padding: 0 0 0 20px;
}

// 弹性布局容器
.flex-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  background: $light-gray;
  padding: 20px 0;
}

::v-deep .el-radio-button__orig-radio + .el-radio-button__inner {
  width: 140px;
}

::v-deep .el-radio-button__orig-radio:checked + .el-radio-button__inner {
  width: 140px;
}

// 自定义表格样式
.custom-table {
  // 科室行样式
  .custom-dept {
    display: flex;
    justify-content: space-between;
    align-items: center;
    border: 1px solid $border-color;
    padding: 0 20px;
    height: 90px;
    margin-bottom: 20px;
    text-align: center;
    font-size: 18px;
    font-weight: bold;

    .col {
      width: calc(100% / 6);

      // 描述文字样式
      .desc {
        font-size: 12px;
        color: $desc-color;
        margin-top: 10px;
        font-weight: normal;
      }
    }

    &:hover {
      border-color: red;
    }
  }
  // 学员注册行样式
  .custom-register {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 14px;
    margin-bottom: 10px;
    height: 150px;

    // 信息区域样式
    .info {
      display: flex;
      justify-content: space-between;
      color: $secondary-color;
      font-size: 14px;

      .flexInfo {
        display: flex;
        flex-direction: column;
        margin-top: 10px;
        box-sizing: border-box;
        line-height: 20px;

        &.left {
          width: 320px;
        }

        &.right {
          width: 220px;
        }
      }
    }

    // 边框样式
    .border {
      border: 1px solid rgba(153, 153, 153, 0.15);
      padding: 10px;
      height: 100%;
      display: flex;
      flex: 1;
      align-items: flex-start;
      flex-direction: column;
      font-size: 12px;

      .desc {
        margin-bottom: 10px;
      }
    }

    // 列样式
    .col {
      .desc {
        color: #666;
        margin-top: 10px;
        font-weight: normal;
      }

      &:nth-child(1) {
        text-align: left;
      }

      &:nth-child(2),
      &:nth-child(3),
      &:nth-child(4),
      &:nth-child(5) {
        width: 150px;
      }
    }
  }
}

::v-deep .el-dialog__body {
  max-height: 80vh;
  overflow-y: auto;
}
</style>
